package com.dragon.mmochat.service;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.message.Mmochat_1_16S;
import com.dragon.mmochat.message.Mmochat_1_7S;
import com.dragon.mmochat.message.Mmochat_5_11C;
import com.dragon.mmochat.message.Mmochat_5_12C;
import com.dragon.mmochat.message.Mmochat_5_14C;
import com.dragon.mmochat.message.Mmochat_5_15C;
import com.dragon.mmochat.message.Mmochat_5_16C;
import com.dragon.mmochat.message.Mmochat_5_17C;
import com.dragon.mmochat.message.Mmochat_5_18C;
import com.dragon.mmochat.message.Mmochat_5_1S;
import com.dragon.mmochat.message.Mmochat_5_21C;
import com.dragon.mmochat.message.Mmochat_5_22C;
import com.dragon.mmochat.message.Mmochat_5_23C;
import com.dragon.mmochat.message.Mmochat_5_24C;
import com.dragon.mmochat.message.Mmochat_5_27C;
import com.dragon.mmochat.message.Mmochat_5_29C;
import com.dragon.mmochat.message.Mmochat_5_2C;
import com.dragon.mmochat.message.Mmochat_5_31S;
import com.dragon.mmochat.message.Mmochat_5_32C;
import com.dragon.mmochat.message.Mmochat_5_33C;
import com.dragon.mmochat.message.Mmochat_5_34C;
import com.dragon.mmochat.message.Mmochat_5_3C;
import com.dragon.mmochat.message.Mmochat_5_4C;
import com.dragon.mmochat.message.Mmochat_5_5C;
import com.dragon.mmochat.message.Mmochat_5_6C;
import com.dragon.mmochat.message.Mmochat_5_7C;
import com.dragon.mmochat.message.Mmochat_5_8C;
import com.dragon.mmochat.message.Mmochat_5_9C;
import com.dragon.mmochat.model.battle.record.MmochatBattleRecord;
import com.dragon.mmochat.model.enumType.MmochatCommonObjectType;
import com.dragon.mmochat.model.enumType.MmochatDrugType;
import com.dragon.mmochat.model.enumType.MmochatEquipPlaceType;
import com.dragon.mmochat.model.enumType.MmochatEquipType;
import com.dragon.mmochat.model.enumType.MmochatMaterialType;
import com.dragon.mmochat.model.enumType.MmochatObjectType;
import com.dragon.mmochat.model.enumType.MmochatPetStateType;
import com.dragon.mmochat.model.enumType.MmochatPropType;
import com.dragon.mmochat.model.enumType.MmochatSecondRoleType;
import com.dragon.mmochat.model.enumType.MmochatServerType;
import com.dragon.mmochat.model.enumType.MmochatSmallMoneyEarnType;
import com.dragon.mmochat.model.enumType.MmochatTeamStateType;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.object.MmochatCommonObject;
import com.dragon.mmochat.model.object.MmochatDrug;
import com.dragon.mmochat.model.object.MmochatEquip;
import com.dragon.mmochat.model.object.MmochatMaterial;
import com.dragon.mmochat.model.object.MmochatPackageGrid;
import com.dragon.mmochat.model.object.MmochatProp;
import com.dragon.mmochat.model.role.MmochatPet;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.util.CallLocalFuncTlv;
import com.dragon.mmochat.util.CreateKeyEventTlvWin;
import com.dragon.mmochat.util.CreateTlvWin;
import com.dragon.mmochat.util.MmochatUtil;
import com.dragon.mmochat.util.SendBigPackUtil;
import com.dragon.mmochat.util.TlvKeyEvent;
import com.google.gson.reflect.TypeToken;
import com.skymobi.handler.SkymobiHandler;
import com.skymobi.message.SkymobiProtocolMessage;
import com.skymobi.message.widget.AddDataTLV;
import com.skymobi.message.widget.ClearDataTLV;
import com.skymobi.message.widget.CloseWinTLV;
import com.skymobi.message.widget.CreateMsgBoxTLV;
import com.skymobi.message.widget.CtrlTLVStructureRequest;
import com.skymobi.message.widget.SendDataTLV;
import com.skymobi.message.widget.ShowPopupMenuTLV;
import com.skymobi.message.widget.ShowWaitingMsgBoxTLV;
import com.skymobi.message.widget.TLVStructure;
import com.skymobi.message.widget.WinType;
import com.skymobi.service.SkymobiService;
import com.skymobi.util.Text;

public class MmochatPackageService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatPackageService.class);

	// 显示物品信息
	private static CreateTlvWin getObjInfo(MmochatCommonObject e) {
		if (e == null) {
			return null;
		}
		CreateTlvWin tlv = new CreateTlvWin();
		tlv.setWinType(WinType.Text);
		tlv.setRightName("返回");
		tlv.setTitle(e.getName());
		tlv.setWinHeight(208);
		tlv.addRightTLV(new CloseWinTLV());
		String detail = e.getInfo();
		tlv.setContent(new Text(detail));

		return tlv;
	}

	// 5.7 查看物品信息(可能被其它玩家查看)
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_7(SkymobiHandler handler,
			Mmochat_5_7C req) {
		MmochatPlayer p = MmochatMainService.players.get(req.getRoleId());
		if (p == null) {
			return MmochatUtil.msgbox(req.getHallState(), "该用户已下线，无法查看!");
		}
		int objId = req.getEquipId();
		if (objId > 0) {
			MmochatCommonObject e = p.getPackageObjById(req.getEquipId());
			if (e == null) {
				return MmochatUtil.msgbox(req.getHallState(), "此物品已转移或不存在!");
			}
			CreateTlvWin tlv = getObjInfo(e);
			return MmochatUtil.tlvResponse(req.getHallState(), tlv);
		} else if (objId == 0) {
			// 人物信息
			CreateTlvWin tlv = new CreateTlvWin();
			tlv.setWinType(WinType.Text);
			tlv.setRightName("返回");
			tlv.setTitle("角色信息");
			tlv.setWinHeight(208);
			tlv.addRightTLV(new CloseWinTLV());
			String detail = MmochatPlayerService.getUserAttrInfo(p);
			tlv.setContent(new Text(detail));
			return MmochatUtil.tlvResponse(req.getHallState(), tlv);
		} else if (objId < 0 && objId > MmochatChatService.baseBattleIdInChat) {
			// 宠物信息
			int petId = -1 * objId;
			MmochatPet pet = p.getPets().get(petId);
			if (pet == null) {
				return MmochatUtil.msgbox(req.getHallState(), "此宠物已转移或不存在!");
			}
			CreateTlvWin tlv = new CreateTlvWin();
			tlv.setWinType(WinType.Text);
			tlv.setRightName("返回");
			tlv.setTitle("宠物信息");
			tlv.setWinHeight(208);
			tlv.addRightTLV(new CloseWinTLV());
			String detail = pet.getPetDealInfo();
			tlv.setContent(new Text(detail));
			return MmochatUtil.tlvResponse(req.getHallState(), tlv);
		} else if (objId <= MmochatChatService.baseBattleIdInChat) {
			// 战斗录像
			int recordId = objId - MmochatChatService.baseBattleIdInChat;
			MmochatBattleRecord record = MmochatBattleService.battleRecords
					.get(recordId);
			if (record == null) {
				return MmochatUtil.msgbox(req.getHallState(), "此战斗录像已过期!");
			}
			// 通过skyId查找用户
			Integer roleId = MmochatMainService.players_skyIdMap.get(req
					.getSkyId());
			MmochatPlayer me = MmochatMainService.getRoleFromBuffer(roleId);
			if (me != null) {
				MmochatMap curMap = MmochatMapService.getMapByMapId(me
						.getMapId());
				if (!curMap.isCanWatchPk()) {
					return MmochatUtil.msgbox(req.getHallState(),
							"本地图内不允许观看录像!");
				}
				if (MmochatTeamService.getTeamState(me) == MmochatTeamStateType.队员) {
					return MmochatUtil.msgbox(req.getHallState(),
							"在队伍中不允许观看录像!");
				}
				if (me.isInBattle() || me.isInWatchingBattle()) {
					return null;
				}
				MmochatBattleService.watchBattleRecord(roleId, recordId);
			}
		}
		return MmochatUtil.msgbox(req.getHallState(), "此物品已转移或不存在!");
	}

	// 5.21 一键补蓝补血
	@SuppressWarnings("unchecked")
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_21(SkymobiHandler handler,
			Mmochat_5_21C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return null;
		}
		if (!me.canAutoUseDrug()) {
			return null;
		}
		boolean needUpdateSql = false;// 使用道具的情况下才保存数据库
		List<MmochatCommonObject> drugs = me.getFirstPageDrugs();

		me.setLatestAutoAddBloodSpritTime();

		int needBlood = 0, needSprit = 0;
		int petNeedBlood = 0, petNeedSprit = 0;
		int bakpetNeedBlood = 0, bakpetNeedSprit = 0;

		int totalBlood = me.getTotalBlood(), totalSprit = me.getTotalSprit();
		int petTotalBlood = 0, petTotalSprit = 0;
		int bakpetTotalBlood = 0, bakpetTotalSprit = 0;

		if (me.getCurBlood() < totalBlood) {
			needBlood = totalBlood - me.getCurBlood();
		}
		if (me.getCurSprit() < totalSprit) {
			needSprit = totalSprit - me.getCurSprit();
		}
		MmochatPet pet = me.getPkPet();
		if (pet != null) {
			petTotalBlood = pet.getTotalBlood();
			petTotalSprit = pet.getTotalSprit();
			if (pet.getCurBlood() < petTotalBlood) {
				petNeedBlood = petTotalBlood - pet.getCurBlood();
			}
			if (pet.getCurSprit() < petTotalSprit) {
				petNeedSprit = petTotalSprit - pet.getCurSprit();
			}
		}

		MmochatPet bakpet = me.getBakPkPet();
		if (bakpet != null) {
			bakpetTotalBlood = bakpet.getTotalBlood();
			bakpetTotalSprit = bakpet.getTotalSprit();
			if (bakpet.getCurBlood() < bakpetTotalBlood) {
				bakpetNeedBlood = bakpetTotalBlood - bakpet.getCurBlood();
			}
			if (bakpet.getCurSprit() < bakpetTotalSprit) {
				bakpetNeedSprit = bakpetTotalSprit - bakpet.getCurSprit();
			}
		}

		if (needBlood == 0 && needSprit == 0 && petNeedBlood == 0
				&& petNeedSprit == 0 && bakpetNeedBlood == 0
				&& bakpetNeedSprit == 0) {
			MmochatChatService.sendSystemMsgToPerson(me, "一键补给功能:当前状态良好,无需用药");
			return null;
		}

		int oldNeedBlood = needBlood, oldNeedSprit = needSprit;
		int oldPetNeedBlood = petNeedBlood, oldPetNeedSprit = petNeedSprit;
		int oldBakPetNeedBlood = bakpetNeedBlood, oldBakPetNeedSprit = bakpetNeedSprit;

		int bloodBeforeUseProp = me.getCurBlood();
		int spritBeforeUseProp = me.getCurSprit();
		int petBloodBeforeUseProp = 0;
		int petSpritBeforeUseProp = 0;
		int bakpetBloodBeforeUseProp = 0;
		int bakpetSpritBeforeUseProp = 0;
		if (pet != null) {
			petBloodBeforeUseProp = pet.getCurBlood();
			petSpritBeforeUseProp = pet.getCurSprit();
		}
		if (bakpet != null) {
			bakpetBloodBeforeUseProp = bakpet.getCurBlood();
			bakpetSpritBeforeUseProp = bakpet.getCurSprit();
		}
		Map<Integer, MmochatPackageGrid> packageBak = (Map<Integer, MmochatPackageGrid>) MmochatUtil
				.deepClone(me.getMyPackage(),
						new TypeToken<Map<Integer, MmochatPackageGrid>>() {
						}.getType());
		// 对药品按加血加蓝值从大到小排序
		if (drugs != null && drugs.size() > 0) {
			Collections.sort(drugs, new MmochatCommonObject.sortDrug());
			for (MmochatCommonObject drug : drugs) {
				if (drug.getOverlapNum() <= 0) {
					continue;
				}
				if (needBlood <= 0 && needSprit <= 0 && petNeedBlood <= 0
						&& petNeedSprit <= 0 && bakpetNeedBlood <= 0
						&& bakpetNeedSprit <= 0) {
					break;
				}

				int drugBlood = drug.getDrugType().getBlood();
				int drugSprit = drug.getDrugType().getSprit();
				if (drugBlood > 0) {
					int needNum = Math.min(needBlood / drugBlood, drug
							.getOverlapNum());
					if (needNum > 0) {
						me.addCurBlood(needNum * drugBlood);
						needBlood -= needNum * drugBlood;
						me.delPackageObj(drug.getDrugType(), needNum);
					}
					int petNeedNum = Math.min(petNeedBlood / drugBlood, drug
							.getOverlapNum());
					if (petNeedNum > 0) {
						pet.addCurBlood(petNeedNum * drugBlood);
						petNeedBlood -= petNeedNum * drugBlood;
						me.delPackageObj(drug.getDrugType(), petNeedNum);
					}

					petNeedNum = Math.min(bakpetNeedBlood / drugBlood, drug
							.getOverlapNum());
					if (petNeedNum > 0) {
						bakpet.addCurBlood(petNeedNum * drugBlood);
						bakpetNeedBlood -= petNeedNum * drugBlood;
						me.delPackageObj(drug.getDrugType(), petNeedNum);
					}
				}
				if (drugSprit > 0) {
					int needNum = Math.min(needSprit / drugSprit, drug
							.getOverlapNum());
					if (needNum > 0) {
						me.addCurSprit(needNum * drugSprit);
						needSprit -= needNum * drugSprit;
						me.delPackageObj(drug.getDrugType(), needNum);
					}
					int petNeedNum = Math.min(petNeedSprit / drugSprit, drug
							.getOverlapNum());
					if (petNeedNum > 0) {
						pet.addCurSprit(petNeedNum * drugSprit);
						petNeedSprit -= petNeedNum * drugSprit;
						me.delPackageObj(drug.getDrugType(), petNeedNum);
					}
					petNeedNum = Math.min(bakpetNeedSprit / drugSprit, drug
							.getOverlapNum());
					if (petNeedNum > 0) {
						bakpet.addCurSprit(petNeedNum * drugSprit);
						bakpetNeedSprit -= petNeedNum * drugSprit;
						me.delPackageObj(drug.getDrugType(), petNeedNum);
					}
				}
			}
		}

		Map<Integer, MmochatPackageGrid> grids = new HashMap<Integer, MmochatPackageGrid>();
		if (needBlood > 0 || petNeedBlood > 0 || needSprit > 0
				|| petNeedSprit > 0 || bakpetNeedBlood > 0
				|| bakpetNeedSprit > 0) {
			for (MmochatPackageGrid grid : me.getMyPackage().values()) {
				// 使用血玲珑补血
				if (!grid.isCanUse() || grid.getObject() == null) {
					continue;
				}
				MmochatCommonObject prop = grid.getObject();
				if (prop.getObjectType() != MmochatObjectType.道具) {
					continue;
				}
				if (prop.getPropType() == MmochatPropType.小血玲珑
						|| prop.getPropType() == MmochatPropType.中血玲珑
						|| prop.getPropType() == MmochatPropType.大血玲珑
						|| prop.getPropType() == MmochatPropType.小血瓶
						|| prop.getPropType() == MmochatPropType.中血瓶
						|| prop.getPropType() == MmochatPropType.大血瓶) {
					if (needBlood > 0) {
						// 给人补血,直接补满
						needUpdateSql = true;
						if (prop.getCurPropAmount() > 0) {
							int bloodNeed = Math.min(needBlood, prop
									.getCurPropAmount());
							prop.use(bloodNeed);
							grids.put(grid.getGridIndex(), grid);
							me.addCurBlood(bloodNeed);
							needBlood -= bloodNeed;
						}
					}
					if (petNeedBlood > 0) {
						// 给宠补血,直接补满
						needUpdateSql = true;
						if (prop.getCurPropAmount() > 0) {
							int bloodNeed = Math.min(petNeedBlood, prop
									.getCurPropAmount());
							prop.use(bloodNeed);
							grids.put(grid.getGridIndex(), grid);
							pet.addCurBlood(bloodNeed);
							petNeedBlood -= bloodNeed;
						}
					}
					if (bakpetNeedBlood > 0) {
						// 给宠补血,直接补满
						needUpdateSql = true;
						if (prop.getCurPropAmount() > 0) {
							int bloodNeed = Math.min(bakpetNeedBlood, prop
									.getCurPropAmount());
							prop.use(bloodNeed);
							grids.put(grid.getGridIndex(), grid);
							bakpet.addCurBlood(bloodNeed);
							bakpetNeedBlood -= bloodNeed;
						}
					}
					if (prop.isUsedOut()) {
						grid.setObject(null);
					}
				} else if (prop.getPropType() == MmochatPropType.小法玲珑
						|| prop.getPropType() == MmochatPropType.中法玲珑
						|| prop.getPropType() == MmochatPropType.大法玲珑) {
					if (needSprit > 0) {
						// 给人补法,直接补满
						needUpdateSql = true;
						if (prop.getCurPropAmount() > 0) {
							int spritNeed = Math.min(needSprit, prop
									.getCurPropAmount());
							prop.use(spritNeed);
							grids.put(grid.getGridIndex(), grid);
							me.addCurSprit(spritNeed);
							needSprit -= spritNeed;
						}
					}
					if (petNeedSprit > 0) {
						// 给宠补法,直接补满
						needUpdateSql = true;
						if (prop.getCurPropAmount() > 0) {
							int spritNeed = Math.min(petNeedSprit, prop
									.getCurPropAmount());
							prop.use(spritNeed);
							grids.put(grid.getGridIndex(), grid);
							pet.addCurSprit(spritNeed);
							petNeedSprit -= spritNeed;
						}
					}
					if (bakpetNeedSprit > 0) {
						// 给宠补法,直接补满
						needUpdateSql = true;
						if (prop.getCurPropAmount() > 0) {
							int spritNeed = Math.min(bakpetNeedSprit, prop
									.getCurPropAmount());
							prop.use(spritNeed);
							grids.put(grid.getGridIndex(), grid);
							bakpet.addCurSprit(spritNeed);
							bakpetNeedSprit -= spritNeed;
						}
					}
					if (prop.isUsedOut()) {
						grid.setObject(null);
					}
				}
				if (needBlood <= 0 && needSprit <= 0 && petNeedBlood <= 0
						&& petNeedSprit <= 0 && bakpetNeedBlood <= 0
						&& bakpetNeedSprit <= 0) {
					break;
				}
			}
		}
		if (needBlood > totalBlood * 0.5 || petNeedBlood > petTotalBlood * 0.5
				|| bakpetNeedBlood > bakpetTotalBlood * 0.5
				|| needSprit > totalSprit * 0.5
				|| petNeedSprit > petTotalSprit * 0.5
				|| bakpetNeedSprit > bakpetTotalSprit * 0.5) {
			// 血蓝少于一半时，强制使用最小的血蓝药
			Collections.reverse(drugs);
			for (MmochatCommonObject drug : drugs) {
				if (drug.getOverlapNum() > 0) {
					if (needBlood <= totalBlood * 0.5
							&& needSprit <= totalSprit * 0.5
							&& petNeedBlood <= petTotalBlood * 0.5
							&& petNeedSprit <= petTotalSprit * 0.5
							&& bakpetNeedBlood <= bakpetTotalBlood * 0.5
							&& bakpetNeedSprit <= bakpetTotalSprit * 0.5) {
						break;
					}

					int drugBlood = drug.getDrugType().getBlood();
					int drugSprit = drug.getDrugType().getSprit();
					if (drugBlood > 0) {
						int needNum = 0;
						if (needBlood > totalBlood * 0.5) {
							needNum = 1;
						}
						if (needNum > 0) {
							me.addCurBlood(needNum * drugBlood);
							needBlood -= needNum * drugBlood;
							me.delPackageObj(drug.getDrugType(), needNum);
						}
						int petNeedNum = 0;
						if (petNeedBlood > petTotalBlood * 0.5) {
							petNeedNum = 1;
						}
						if (petNeedNum > 0) {
							pet.addCurBlood(petNeedNum * drugBlood);
							petNeedBlood -= petNeedNum * drugBlood;
							me.delPackageObj(drug.getDrugType(), petNeedNum);
						}

						petNeedNum = 0;
						if (bakpetNeedBlood > bakpetTotalBlood * 0.5) {
							petNeedNum = 1;
						}
						if (petNeedNum > 0) {
							bakpet.addCurBlood(petNeedNum * drugBlood);
							bakpetNeedBlood -= petNeedNum * drugBlood;
							me.delPackageObj(drug.getDrugType(), petNeedNum);
						}
					}
					if (drugSprit > 0) {
						int needNum = 0;
						if (needSprit > totalSprit * 0.5) {
							needNum = 1;
						}
						if (needNum > 0) {
							me.addCurSprit(needNum * drugSprit);
							needSprit -= needNum * drugSprit;
							me.delPackageObj(drug.getDrugType(), needNum);
						}
						int petNeedNum = 0;
						if (petNeedSprit > petTotalSprit * 0.5) {
							petNeedNum = 1;
						}
						if (petNeedNum > 0) {
							pet.addCurSprit(petNeedNum * drugSprit);
							petNeedSprit -= petNeedNum * drugSprit;
							me.delPackageObj(drug.getDrugType(), petNeedNum);
						}

						petNeedNum = 0;
						if (bakpetNeedSprit > bakpetTotalSprit * 0.5) {
							petNeedNum = 1;
						}
						if (petNeedNum > 0) {
							bakpet.addCurSprit(petNeedNum * drugSprit);
							bakpetNeedSprit -= petNeedNum * drugSprit;
							me.delPackageObj(drug.getDrugType(), petNeedNum);
						}
					}
				}
			}
		}

		if (oldNeedBlood == needBlood && oldNeedSprit == needSprit
				&& oldPetNeedBlood == petNeedBlood
				&& oldPetNeedSprit == petNeedSprit
				&& oldBakPetNeedBlood == bakpetNeedBlood
				&& oldBakPetNeedSprit == bakpetNeedSprit) {
			MmochatChatService.sendSystemMsgToPerson(me,
					"一键补给功能:没有合适的小药补充气血灵力(只使用第一页包裹中的药品)");
			return null;
		} else {
			if (needUpdateSql) {
				try {
					MmochatDao.updateMyPackage(me);
				} catch (Exception e) {
					e.printStackTrace();
					me.setCurBlood(bloodBeforeUseProp);
					me.setCurSprit(spritBeforeUseProp);
					if (pet != null) {
						pet.setCurBlood(petBloodBeforeUseProp);
						pet.setCurSprit(petSpritBeforeUseProp);
					}
					if (bakpet != null) {
						bakpet.setCurBlood(bakpetBloodBeforeUseProp);
						bakpet.setCurSprit(bakpetSpritBeforeUseProp);
					}
					me.setMyPackage(packageBak);
					return null;
				}
			}
			if (grids.size() > 0) {
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack
						.setGrids(new ArrayList<MmochatPackageGrid>(grids
								.values()));
				MmochatUtil.sendCommonPack(me, pack);
			}
			// 更新人宠头像信息
			Mmochat_1_7S pack = new Mmochat_1_7S();
			pack.setMe(me);
			return pack;
		}
	}

	// 5.6 使用物品
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_6(SkymobiHandler handler,
			Mmochat_5_6C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}

		MmochatPackageGrid grid = me.getMyPackage().get(req.getGridId());
		if (grid == null || !grid.isCanUse()) {
			return null;
		}

		MmochatCommonObject obj = grid.getObject();
		if (obj == null) {
			return null;
		}

		if (obj.isUsedOut()) {
			grid.setObject(null);
			// 下发更新包裹数据
			Mmochat_5_1S pack = new Mmochat_5_1S();
			pack.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack);
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}

		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			if (obj.getObjectType() != MmochatObjectType.装备) {
				return MmochatUtil.msgbox(req.getHallState(),
						"跨服区内只能使用装备，其它物品无法使用。");
			}
		}

		switch (obj.getObjectType()) {
		case 药品: {
			synchronized (me) {
				// 此格子可能被并发线程修改，需要重新读取
				grid = me.getMyPackage().get(req.getGridId());
				if (grid == null || !grid.isCanUse()) {
					return null;
				}

				obj = grid.getObject();
				if (obj == null) {
					return null;
				}
				if (obj.isUsedOut()) {
					grid.setObject(null);
					// 下发更新包裹数据
					Mmochat_5_1S pack = new Mmochat_5_1S();
					pack.addGrid(grid);
					MmochatUtil.sendCommonPack(me, pack);
					return MmochatUtil
							.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
				}

				MmochatDrugType type = obj.getDrugType();
				if (type.getBlood() <= 0 && type.getSprit() <= 0) {
					return MmochatUtil.msgbox(req.getHallState(), "此药品无法食用!");
				}
				boolean used = false;
				if (type.getBlood() > 0) {
					// 补血
					if (me.getCurBlood() < me.getTotalBlood()) {
						me.addCurBlood(type.getBlood());
						used = true;
					}
				}
				if (type.getSprit() > 0) {
					// 补蓝
					if (me.getCurSprit() < me.getTotalSprit()) {
						me.addCurSprit(type.getSprit());
						used = true;
					}
				}
				if (!used) {
					return MmochatUtil.msgbox(req.getHallState(),
							"当前状态良好,无需食用此药!");
				}
				obj.delOverlapNum(1);
				if (obj.getOverlapNum() <= 0) {
					grid.setObject(null);
				}
			}
			// 更新药品和人气血状态
			try {
				MmochatDao.updateRoleAfterEatDrug(me);
			} catch (Exception e) {
				e.printStackTrace();
				return MmochatUtil.msgbox(req.getHallState(), "当前数据库忙,请稍候再试!");
			}
			// 更新人物头像信息
			Mmochat_1_7S pack = new Mmochat_1_7S();
			pack.setMe(me);
			MmochatUtil.sendCommonPack(me, pack);

			// 下发更新包裹数据
			Mmochat_5_1S pack1 = new Mmochat_5_1S();
			pack1.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack1);

			return null;
		}
		case 装备: {
			synchronized (me) {
				// 此格子可能被并发线程修改，需要重新读取
				grid = me.getMyPackage().get(req.getGridId());
				if (grid == null || !grid.isCanUse()) {
					return null;
				}

				obj = grid.getObject();
				if (obj == null) {
					return null;
				}
				if (obj.isUsedOut()) {
					grid.setObject(null);
					// 下发更新包裹数据
					Mmochat_5_1S pack = new Mmochat_5_1S();
					pack.addGrid(grid);
					MmochatUtil.sendCommonPack(me, pack);
					return MmochatUtil
							.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
				}

				MmochatEquipPlaceType place = MmochatEquipPlaceType.get(req
						.getGridId());
				if (place != null) {
					// 卸下装备
					if (!me.hasEnoughPackageSpace(1)) {
						return MmochatUtil.msgbox(req.getHallState(),
								"包裹已满,无法卸下!");
					}
					// 判断卸下之前是否是一身套装
					boolean isSet = me.isAllWeaponedEquipTheSameSet();

					// 更新装备使用者
					grid.getObject().setEquipUserRoleId(null);
					me.addObjectToPackage(grid.getObject());
					grid.setObject(null);
					// 下发更新包裹数据
					Mmochat_5_1S pack = new Mmochat_5_1S();
					if (isSet) {
						// 如果是套装，需要更新4件套装备和套装效果
						MmochatPackageGrid grid1 = me.getMyPackage().get(
								MmochatEquipPlaceType.头部.getValue());
						if (grid1 != null) {
							pack.addGrid(grid1);
						}
						grid1 = me.getMyPackage().get(
								MmochatEquipPlaceType.手上.getValue());
						if (grid1 != null) {
							pack.addGrid(grid1);
						}
						grid1 = me.getMyPackage().get(
								MmochatEquipPlaceType.身体.getValue());
						if (grid1 != null) {
							pack.addGrid(grid1);
						}
						grid1 = me.getMyPackage().get(
								MmochatEquipPlaceType.脚.getValue());
						if (grid1 != null) {
							pack.addGrid(grid1);
						}

						// 更新套装效果
						Mmochat_1_16S effect = new Mmochat_1_16S();
						effect.setMe(me);
						MmochatUtil.sendCommonPack(me, effect);
					}
					pack.addGrid(grid);
					MmochatUtil.sendCommonPack(me, pack);
				} else {
					// 使用装备
					if (me.getLevel() < obj.getEquipLevelNeed()) {
						return MmochatUtil.msgbox(req.getHallState(),
								"等级不够,无法使用此装备!");
					}
					if (me.getLife_turn() < obj.getLife_turn()) {
						return MmochatUtil.msgbox(req.getHallState(), "此装备至少需要"
								+ obj.getLife_turn() + "次转生才能驾驭!");
					}
					if (obj.getSecond_role_type() != MmochatSecondRoleType.未转生) {
						if (me.getSecond_role_type() != obj
								.getSecond_role_type()) {
							return MmochatUtil.msgbox(req.getHallState(),
									"此装备属"
											+ MmochatUtil.wrapColor(obj
													.getSecond_role_type()
													.toString(), Color.yellow)
											+ "装备，您无法使用");
						}
					}
					// 使用装备之前是否一身套装
					boolean isSetBefore = me.isAllWeaponedEquipTheSameSet();
					MmochatPackageGrid placeGrid = null;
					if (obj.getEquipType() == MmochatEquipType.手镯) {
						placeGrid = me.getMyPackage().get(
								MmochatEquipPlaceType.左手腕.getValue());
						if (placeGrid != null && placeGrid.getObject() != null) {
							placeGrid = me.getMyPackage().get(
									MmochatEquipPlaceType.右手腕.getValue());
						}
					} else {
						place = MmochatEquipPlaceType.get(obj.getEquipType());
						placeGrid = me.getMyPackage().get(place.getValue());
					}
					if (placeGrid != null) {
						MmochatCommonObject oldObj = placeGrid.getObject();
						placeGrid.setObject(obj);
						grid.setObject(oldObj);
						// 更新装备使用者
						if (oldObj != null) {
							oldObj.setEquipUserRoleId(null);
						}
						obj.setEquipUserRoleId(me.getRoleId());

						// 使用装备之后是否一身套装
						boolean isSetAfter = me.isAllWeaponedEquipTheSameSet();
						// 下发更新包裹数据
						Mmochat_5_1S pack = new Mmochat_5_1S();
						if (isSetBefore || isSetAfter) {
							// 如果是套装，需要更新4件套装备
							MmochatPackageGrid grid1 = me.getMyPackage().get(
									MmochatEquipPlaceType.头部.getValue());
							if (grid1 != null) {
								pack.addGrid(grid1);
							}
							grid1 = me.getMyPackage().get(
									MmochatEquipPlaceType.手上.getValue());
							if (grid1 != null) {
								pack.addGrid(grid1);
							}
							grid1 = me.getMyPackage().get(
									MmochatEquipPlaceType.身体.getValue());
							if (grid1 != null) {
								pack.addGrid(grid1);
							}
							grid1 = me.getMyPackage().get(
									MmochatEquipPlaceType.脚.getValue());
							if (grid1 != null) {
								pack.addGrid(grid1);
							}

							// 更新套装效果
							Mmochat_1_16S effect = new Mmochat_1_16S();
							effect.setMe(me);
							MmochatUtil.sendCommonPack(me, effect);
						}
						pack.addGrid(placeGrid);
						pack.addGrid(grid);
						MmochatUtil.sendCommonPack(me, pack);
					}
				}
			}
			return null;
		}
		case 道具: {
			// 使用道具
			Map<Integer, Object> msg = MmochatPropService.useProp(me, req
					.getGridId(), me);
			String errMsg = (String) msg.get(0);
			String successMsg = (String) msg.get(1);
			TLVStructure propTlv = (TLVStructure) msg.get(2);
			Boolean ret = (Boolean) msg.get(3);

			if (ret != null) {
				// 直接返回
				return null;
			}
			if (errMsg != null) {
				return MmochatUtil.msgbox(req.getHallState(), errMsg);
			}

			if (propTlv != null) {
				return MmochatUtil.tlvResponse(req.getHallState(), propTlv);
			} else {
				CreateMsgBoxTLV msgbox = new CreateMsgBoxTLV();
				if (successMsg == null) {
					successMsg = "使用成功!";
				}
				msgbox.setContent(new Text(successMsg));
				msgbox.setLeftName("确定");
				return MmochatUtil.tlvResponse(req.getHallState(), msgbox);
			}
		}
		case 法宝: {
			// 使用法宝
			synchronized (me) {
				// 此格子可能被并发线程修改，需要重新读取
				grid = me.getMyPackage().get(req.getGridId());
				if (grid == null || !grid.isCanUse()) {
					return null;
				}

				obj = grid.getObject();
				if (obj == null) {
					return null;
				}
				if (obj.isUsedOut()) {
					grid.setObject(null);
					// 下发更新包裹数据
					Mmochat_5_1S pack = new Mmochat_5_1S();
					pack.addGrid(grid);
					MmochatUtil.sendCommonPack(me, pack);
					return MmochatUtil
							.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
				}

				MmochatEquipPlaceType place = MmochatEquipPlaceType.get(req
						.getGridId());
				if (place != null) {
					// 卸下法宝
					if (!me.hasEnoughPackageSpace(1)) {
						return MmochatUtil.msgbox(req.getHallState(),
								"包裹已满,无法卸下!");
					}
					me.addObjectToPackage(grid.getObject());
					grid.setObject(null);
					// 下发更新包裹数据
					Mmochat_5_1S pack = new Mmochat_5_1S();
					pack.addGrid(grid);
					MmochatUtil.sendCommonPack(me, pack);
				} else {
					// 使用法宝
					MmochatPackageGrid placeGrid = null;
					placeGrid = me.getMyPackage().get(
							grid.getObject().getSuperMachineType().getGridId());

					if (placeGrid != null) {
						MmochatCommonObject oldObj = placeGrid.getObject();
						placeGrid.setObject(obj);
						grid.setObject(oldObj);

						// 下发更新包裹数据
						Mmochat_5_1S pack = new Mmochat_5_1S();
						pack.addGrid(grid);
						pack.addGrid(placeGrid);
						MmochatUtil.sendCommonPack(me, pack);
					}
				}
			}
			// 更新人物状态
			Mmochat_1_16S pack = new Mmochat_1_16S();
			pack.setMe(me);
			MmochatUtil.sendCommonPack(me, pack);
			return null;
		}
		default:
			break;
		}
		return MmochatUtil.msgbox(req.getHallState(), "此物品无法直接使用!");
	}

	// 5.32 丟弃物品
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_32(SkymobiHandler handler,
			Mmochat_5_32C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			return MmochatUtil.msgbox(req.getHallState(), "跨服区无法使用此功能!");
		}
		if (MmochatNpcService.checkStorePwd(me)) {
			return null;
		}

		MmochatPackageGrid grid;
		synchronized (me) {
			grid = me.getMyPackage().get(req.getGridId());
			if (grid == null || !grid.isCanUse() || grid.getObject() == null) {
				return null;
			}
			MmochatCommonObject obj = grid.getObject();
			if (!grid.getObject().isCanDrop()) {
				return MmochatUtil.msgbox(req.getHallState(), "此物品无法遗弃!");
			}

			// 改造过的装备、粉装、绿装不能遗弃，只能回收；赠品只能遗弃
			if (obj.getEquipModifyLevel() > 0 || obj.getEquipPinkAttr() != null
					|| obj.getEquipGreenDarkAttr() != null
					|| obj.getEquipType() == MmochatEquipType.玉佩
					|| obj.getEquipType() == MmochatEquipType.挂坠
					|| obj.getEquipType() == MmochatEquipType.手镯
					|| obj.getSuperMachineType() != null) {
				if (obj.isCanDeal()) {
					// 非赠品
					return MmochatUtil.msgbox(req.getHallState(),
							"改造过的装备、粉装、绿装、首饰、法宝都不能直接遗弃，请到武器店找NPC进行回收!");
				}
			}

			// 如果是武魂石，增加回收记录
			try {
				if (obj.getPkStoneBaseAttr() != null && obj.getPropLevel() > 1) {
					// 回收记录
					List<MmochatCommonObject> list = MmochatNpcService.soldToSystemObjMap
							.get(me.getRoleId());
					if (list == null) {
						list = new ArrayList<MmochatCommonObject>();
					}
					list.add(obj);
					MmochatNpcService.soldToSystemObjMap.put(me.getRoleId(),
							list);
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}

			grid.setObject(null);
			if (obj.canSell()) {
				int price = obj.getPriceOfSellToSystem() * obj.getOverlapNum();
				try {
					MmochatDao.sellEquip(me, price);
				} catch (Exception e) {
					e.printStackTrace();
					grid.setObject(obj);
					return MmochatUtil
							.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
				}
				me.addAndUpdateSmall_money(price);
				MmochatStatisticsService.addSmallMoneyEarn(
						MmochatSmallMoneyEarnType.回收装备, price);
				MmochatChatService.sendSystemMsgToPerson(me, "您遗弃了一件装备，获得了"
						+ MmochatUtil.getColorMoney(price) + "文钱!");
			}
		}

		Mmochat_5_1S pack = new Mmochat_5_1S();
		pack.addGrid(grid);

		return pack;
	}

	// 5.33 移动物品
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_33(SkymobiHandler handler,
			Mmochat_5_33C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}

		synchronized (me) {
			MmochatPackageGrid oldGrid = me.getMyPackage().get(
					req.getOldGridId());
			MmochatPackageGrid newGrid = me.getMyPackage().get(
					req.getNewGridId());
			if (oldGrid == null || !oldGrid.isCanUse()
					|| oldGrid.getObject() == null || newGrid == null
					|| !newGrid.isCanUse() || newGrid.getObject() != null) {
				return null;
			}
			newGrid.setObject(oldGrid.getObject());
			oldGrid.setObject(null);
			try {
				MmochatDao.updateMyPackage(me);
			} catch (Exception e) {
				e.printStackTrace();
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack.addGrid(oldGrid);
				pack.addGrid(newGrid);
				MmochatUtil.sendCommonPack(me, pack);
			}
		}
		return null;
	}

	// 5.34 整理包裹
	@SuppressWarnings("unchecked")
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_34(SkymobiHandler handler,
			Mmochat_5_34C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			return MmochatUtil.msgbox(req.getHallState(), "跨服区无法使用此功能!");
		}
		if (!me.canOrderStorage()) {
			return MmochatUtil.msgbox(req.getHallState(), "请"
					+ me.getRestOrderSec() + "秒后再整理包裹!");
		}
		me.setLastOrderStorageTick(System.currentTimeMillis());
		me.setPropNumBeforeTask();
		synchronized (me) {
			int gridStart = req.getGridStart();
			int gridEnd = req.getGridEnd();
			// 同类物品，如果可叠加，则尽量叠加
			// 排序：药品、道具、装备、材料、法宝
			Map<Integer, MmochatPackageGrid> packageBak = (Map<Integer, MmochatPackageGrid>) MmochatUtil
					.deepClone(me.getMyPackage(),
							new TypeToken<Map<Integer, MmochatPackageGrid>>() {
							}.getType());
			List<MmochatCommonObject> drugList = new ArrayList<MmochatCommonObject>();
			List<MmochatCommonObject> propList = new ArrayList<MmochatCommonObject>();
			List<MmochatCommonObject> equipList = new ArrayList<MmochatCommonObject>();
			List<MmochatCommonObject> materialList = new ArrayList<MmochatCommonObject>();
			List<MmochatCommonObject> machineList = new ArrayList<MmochatCommonObject>();
			List<MmochatCommonObject> otherList = new ArrayList<MmochatCommonObject>();
			List<MmochatPackageGrid> gridList = new ArrayList<MmochatPackageGrid>();
			for (int i = gridStart; i <= gridEnd; i++) {
				MmochatPackageGrid grid = me.getMyPackage().get(i);
				if (!grid.isCanUse()) {
					continue;
				}
				gridList.add(grid);
				if (grid != null && grid.getObject() != null) {
					MmochatCommonObject obj = grid.getObject();
					switch (obj.getObjectType()) {
					case 药品: {
						drugList.add(obj);
						break;
					}
					case 装备: {
						equipList.add(obj);
						break;
					}
					case 材料: {
						materialList.add(obj);
						break;
					}
					case 道具: {
						propList.add(obj);
						break;
					}
					case 法宝: {
						machineList.add(obj);
						break;
					}
					default:
						otherList.add(obj);
						break;
					}
				}
				grid.setObject(null);
			}
			for (MmochatCommonObject machine : machineList) {
				me.addObjectToPackage(machine, gridStart, gridEnd, false);
			}
			if (drugList.size() > 0) {
				// 药品排序
				List<MmochatCommonObject> drugs = new ArrayList<MmochatCommonObject>(
						drugList);
				Collections.sort(drugs, new MmochatCommonObject.sortDrug());
				for (MmochatCommonObject drug : drugs) {
					me.addObjectToPackage(drug, gridStart, gridEnd, false);
				}
			}
			if (propList.size() > 0) {
				Collections.sort(propList, new MmochatCommonObject.sortProp());
				for (MmochatCommonObject prop : propList) {
					me.addObjectToPackage(prop, gridStart, gridEnd, false);
				}
			}
			if (equipList.size() > 0) {
				for (MmochatCommonObject equip : equipList) {
					me.addObjectToPackage(equip, gridStart, gridEnd, false);
				}
			}
			if (materialList.size() > 0) {
				List<MmochatCommonObject> materials = new ArrayList<MmochatCommonObject>(
						materialList);
				Collections.sort(materials,
						new MmochatCommonObject.sortMaterial());
				for (MmochatCommonObject material : materials) {
					me.addObjectToPackage(material, gridStart, gridEnd, false);
				}
			}
			for (MmochatCommonObject other : otherList) {
				me.addObjectToPackage(other, gridStart, gridEnd, false);
			}
			try {
				MmochatDao.updateMyPackage(me);
			} catch (Exception e) {
				e.printStackTrace();
				me.setMyPackage(packageBak);
				me.checkPropNumAfterTask("handleC_5_34,1");
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}
			SendBigPackUtil.sendBigPack_5_1S(me, gridList);
		}
		me.checkPropNumAfterTask("handleC_5_34,2");
		return null;
	}
}
